import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Card, Spin, Table, Input, Modal, Popconfirm} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, PAGE, TABLE, DATETIME_FORMAT, FIXED_COLUMN_WIDTH} from '../constants';
import {conventEnumValueToString, formatAmount, formatDateTime} from '../utils';
import {PERMISSION} from './constants';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import Return from '../common/Return';
import {currency, dealerType} from '../Enum';
import {injectIntl, formatMessage} from './intl';
import ExpandedRowTablePanel from './ExpandedRowTablePanel';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import SearchSelect from 'Shared/components/SearchSelect';
import {getTechnologyActivitySimple, getDealers, getDealerSimple} from './api';
import TechnologyActivitySelectPanel from './TechnologyActivitySelectPanel';
import TechnologyActivityClaimSelectPanel from './TechnologyActivityClaimSelectPanel';
import {newOrderValidator, approveAllValidator, updateOrderValidator} from './validator';
export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        isForwarderSearch: false,
        technologyActivityShow: false,
        claimShow: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };

    labelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `${d.serviceName}`;
        return '';
    }
    onSubmit = () => {
        const isValid = this.props.conditions.id ? updateOrderValidator(this.props.conditions) : newOrderValidator(this.props.conditions);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    onSubmitPass = () => {
        this.setState({
            loading: true
        });
        this.props.onSubmitPass().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    onSubmitReject = () => {
        const isValid = approveAllValidator(this.props.conditions);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true
        });
        this.props.onSubmitReject().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    onSelectDealer = data => {
        const {details = [], dealerId} = this.props.conditions;
        if(!data.id || data.id === dealerId)
            return;
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        if(details.length && data.id !== dealerId)
            return Modal.confirm({
                title: formatMessage({
                    id: 'newPanel.handleCompanyChange.title',
                    defaultMessage: '变更总代将会清空清单，是否变更？'
                }),
                onOk: () => {
                    this.setState({isPrevLoading: true});
                    this.props.onSelectDealer(data);
                },
            });
        this.setState({isPrevLoading: true});
        this.props.onSelectDealer(data);
    }
    
    onSearchTechnologyActivity = value => {
        const {dealerId, brandId} = this.props.conditions;
        return getTechnologyActivitySimple({
            filter: value,
            brandId,
            dealerId
        })
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            });
    }
        
    onSelectTechnologyActivity = data => {
        this.setState({
            technologyActivityShow: false,
            hasOperat: true
        });
        this.props.onSelectTechnologyActivity(data);
    }
    onClickTechnologyActivity = () => {
        this.setState({technologyActivityShow: true});
    }
    onCloseTechnologyActivity = () => {
        this.setState({technologyActivityShow: false});
    }

    onSelectClaim = data => {
        this.setState({
            claimShow: false,
            hasOperat: true
        });
        this.props.onSelectDetails(data);
    }
    onClickAdd = () => {
        this.setState({claimShow: true});
    }
    onCloseClaim = () => {
        this.setState({claimShow: false});
    }
    onClickDelete = e => {
        const {id} = e.target.dataset;
        this.props.onDeleteDetail(id);
    };
    render() {
        const {conditions, id, details = [], loading, page, brands,
            onDeleteAll, submitable, onCancel} = this.props;
        const technologyActivityInfo = conditions.technologyActivityId ? {
            id: conditions.technologyActivityId,
            serviceName: conditions.technologyActivityName
        } : null;
        const dealerInfo = conditions.dealerId ? {
            id: conditions.dealerId,
            code: conditions.dealerCode,
            name: conditions.dealerName
        } : null;
        let laborFee = 0;
        let materialFee = 0;
        let mgmtFee = 0;
        let assistantFee = 0;
        let totalFee = 0;
        // eslint-disable-next-line array-callback-return
        details.map(v => {
            laborFee += v.laborFee;
            materialFee += v.materialFee;
            mgmtFee += v.mgmtFee;
            assistantFee += v.assistantFee;
            totalFee += v.totalFee;
        });
        const validateBrandId = !conditions.brandId && this.state.validate ? 'error' : null;
        const validateDealerId = !conditions.dealerId && this.state.validate ? 'error' : null;
        const validateTechnologyActivityId = !conditions.technologyActivityId && this.state.validate ? 'error' : null;
        const columns = [
            {
                title: formatMessage({
                    id: 'newPanel.column.technologyActivityClaimCode',
                    defaultMessage: '技术升级索赔编号'
                }),
                dataIndex: 'technologyActivityClaimCode',
            },
            {
                title: formatMessage({
                    id: 'newPanel.column.laborFee',
                    defaultMessage: '工时费'
                }),
                dataIndex: 'laborFee',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'newPanel.column.materialFee',
                    defaultMessage: '材料费'
                }),
                dataIndex: 'materialFee',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'newPanel.column.mgmtFee',
                    defaultMessage: '管理费'
                }),
                dataIndex: 'mgmtFee',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'newPanel.column.assistantFee',
                    defaultMessage: '辅料费'
                }),
                dataIndex: 'assistantFee',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'newPanel.column.totalFee',
                    defaultMessage: '总金额'
                }),
                dataIndex: 'totalFee',
                sorter: true,
                className: styles.textAlign,
                render: text => formatAmount(text)
            }
        ];
        if(page !== 'approve')
            columns.push({
                title: details && details.length ? (<Popconfirm
                    placement="topRight"
                    onConfirm={onDeleteAll}
                    title={formatMessage({
                        id: 'newPanel.popconfirm.delete.message',
                        defaultMessage: '是否确认清空?'
                    })}>
                    <a key="clearBtn">
                        {formatMessage({
                            id: 'add.materials.clearBtn',
                            defaultMessage: '清空'
                        })}
                    </a>
                </Popconfirm>)
                    : <a key="clearBtn">
                        {formatMessage({
                            id: 'newPanel.materials.clearBtn',
                            defaultMessage: '清空'
                        })}
                    </a>,
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => <a onClick={this.onClickDelete} key="delete" data-id={record.technologyActivityClaimId}>
                    {formatMessage({
                        id: 'newPanel.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            });
        const dealerComp = conditions.brandId ? (<DealerSelectPanel
            conditions={{
                type: dealerType.总代,
                brandId: conditions.brandId
            }}
            value={dealerInfo}
            getDealerSimple={getDealers}
            getDealers={getDealerSimple}
            onSelect={this.onSelectDealer} />) : (<TextInput name="dealerId"
            value={''} disabled placeholder={formatMessage({
                id: 'newPanel.brandComp.placeholder',
                defaultMessage: '请先选择品牌'
            })} />);
        const technologyActivityComp = conditions.brandId && conditions.dealerId ? (<SearchSelect
            showCopyButton={true}
            value={technologyActivityInfo}
            placeholder={formatMessage({
                id: 'newPanel.form.vin.placeholder',
                defaultMessage: '请输入技术升级主题查询'
            })}
            onSelect={this.onSelectTechnologyActivity}
            onSearch={this.onSearchTechnologyActivity}
            keyIndex="id"
            labelMap={this.labelMap}
            onClickSearchBtn={this.onClickTechnologyActivity} />) : (<TextInput name="dealerId"
            value={''} disabled placeholder={formatMessage({
                id: 'newPanel.brandAndDealerComp.placeholder',
                defaultMessage: '请先选择品牌和总代'
            })} />);
        return (
            <div className={styles.detail}>
                <Spin spinning={loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={formatMessage({
                                id: 'newPanel.card.title',
                                defaultMessage: '技术升级结算'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.sapDeliveryCode',
                                            defaultMessage: '技术升级结算编号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {id ? conditions.code : <Input placeholder={formatMessage({
                                            id: 'newPanel.operation.notGenerate',
                                            defaultMessage: '尚未生成'
                                        })} value={conditions.code} disabled />}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.brandCode',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateBrandId}
                                        required={!id}>
                                        {id ? `(${conditions.brandCode})${conditions.brandName}`
                                            : <div onClick={this.onClickStopPropagation}><WrappedSelect
                                                name="brandId"
                                                options={brands}
                                                value={conditions.brandId}
                                                onChange={this.handleFilterChange} /></div>}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.dealerCode',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateDealerId}
                                        required={!id}>
                                        {id
                                            ? <span className="value-font">{conditions.dealerCode}</span>
                                            : dealerComp}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.currency',
                                            defaultMessage: '币种'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{conventEnumValueToString(currency, conditions.currency)}</span>
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.technologyActivityName',
                                            defaultMessage: '技术升级主题'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateTechnologyActivityId}
                                        required={!id}>
                                        {!id && technologyActivityComp}
                                        {id && conditions.technologyActivityName}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.startTime',
                                            defaultMessage: '开始时间'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(conditions.startTime, DATETIME_FORMAT)}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.endTime',
                                            defaultMessage: '技术升级截止日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(conditions.startTime, DATETIME_FORMAT)}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.laborFee',
                                            defaultMessage: '工时费'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatAmount(laborFee)}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.materialFee',
                                            defaultMessage: '材料费'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatAmount(materialFee)}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.mgmtFee',
                                            defaultMessage: '管理费'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatAmount(mgmtFee)}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.assistantFee',
                                            defaultMessage: '辅料费'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatAmount(assistantFee)}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.totalFee',
                                            defaultMessage: '费用合计'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatAmount(totalFee)}
                                    </Form.Item>
                                </Col>
                            </Row>
                            {page === 'approve' && <Row>
                                <Form.Item
                                    label={formatMessage({
                                        id: 'newPanel.form.approveComment',
                                        defaultMessage: '审核意见'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput
                                        type="textarea"
                                        name="approveComment"
                                        autosize={{minRows: 1}}
                                        value={conditions.approveComment}
                                        onBlur={this.handleFilterChange} />
                                </Form.Item>
                            </Row>}
                            <Row>
                                <Form.Item
                                    label={formatMessage({
                                        id: 'newPanel.form.remark',
                                        defaultMessage: '备注'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput
                                        type="textarea"
                                        name="remark"
                                        autosize={{minRows: 1}}
                                        value={conditions.remark}
                                        onBlur={this.handleFilterChange} />
                                </Form.Item>
                            </Row>
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'newPanel.details.title',
                                defaultMessage: '技术升级结算清单'
                            })}
                            extra={<span className={styles.optionBtn}>
                                {page !== 'approve' && <Button key="addBtn" size="small"
                                    disabled={!conditions.technologyActivityName} onClick={this.onClickAdd}>
                                    {formatMessage({
                                        id: 'add.form.addBtn',
                                        defaultMessage: '新增索赔单'
                                    })}
                                </Button>}
                            </span>}>
                            <Table
                                className="white-space-nowrap"
                                rowKey="technologyActivityClaimId"
                                columns={columns}
                                pagination={false}
                                dataSource={details}
                                expandedRowRender={record => <ExpandedRowTablePanel
                                    data={record.settlementDetails}/>}
                                {...TABLE} />
                        </Card>
                        {submitable && (
                            <Card type="inner">
                                <Row>
                                    {page !== 'approve' && <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            type="primary"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}>
                                            {formatMessage({
                                                id: 'newPanel.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>}
                                    {page === 'approve' &&
                                    <Col className="col-align-right">
                                        <Button
                                            key="submitReject"
                                            loading={this.state.loading}
                                            onClick={this.onSubmitReject}>
                                            {formatMessage({
                                                id: 'newPanel.btn.submitReject',
                                                defaultMessage: '驳回'
                                            })}
                                        </Button>
                                        <Button
                                            key="submitPass"
                                            type="primary"
                                            loading={this.state.loading}
                                            onClick={this.onSubmitPass}>
                                            {formatMessage({
                                                id: 'newPanel.btn.submitPass',
                                                defaultMessage: '审核通过'
                                            })}
                                        </Button>
                                    </Col>
                                    }
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={onCancel} />
                </div>
                {
                    this.state.technologyActivityShow &&
                    <TechnologyActivitySelectPanel
                        brandId={conditions.brandId}
                        dealerId={conditions.dealerId}
                        onCancel={this.onCloseTechnologyActivity}
                        onSelect={this.onSelectTechnologyActivity} />
                }
                {
                    this.state.claimShow &&
                    <TechnologyActivityClaimSelectPanel
                        currentSelectRowkeys={details}
                        technologyActivityId={conditions.technologyActivityId}
                        brandId={conditions.brandId}
                        dealerId={conditions.dealerId}
                        onCancel={this.onCloseClaim}
                        onSelect={this.onSelectClaim} />
                }
                
            </div>
        );
    }
}
NewPanel.propTypes = {
    brands: PropTypes.array.isRequired,
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onSelectDetails: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    onClickAddOrUpdate,
    getEditInit,
    selectCountry,
    selectTechnologyActivity,
    selectDetails,
    deleteAllDetail,
    deleteDetail,
    onClickApprove
} from './actions';
import {createSelector} from 'reselect';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getBrandsData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    initData => {
        const data = initData.toJS() || [];
        return data.map(item => ({
            text: item.name,
            value: item.id
        }));
    }
);
const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    (state, ownProps) => ownProps.id,
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, id, detail) => {
        const {options = []} = detail.toJS();
        const data = permissions.toJS();
        const submitable = id ? data.includes(PERMISSION.update) || options.includes(PERMISSION.approve)
            : data.includes(PERMISSION.add);
        return submitable;
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getSubmitData(state),
    brands: getBrandsData(state)
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getEditInit(ownProps.id)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: status =>
        dispatch(onClickAddOrUpdate(ownProps.id, status)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onSubmitPass: () =>
        dispatch(onClickApprove(true)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onSubmitReject: () =>
        dispatch(onClickApprove(false)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    onSelectDealer: data => dispatch(selectCountry(data)),
    onSelectTechnologyActivity: data => dispatch(selectTechnologyActivity(data)),
    onSelectDetails: data => dispatch(selectDetails(data)),
    onDeleteAll: () => dispatch(deleteAllDetail()),
    onDeleteDetail: id => dispatch(deleteDetail(id)),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(NewPanel));
